import axios from "axios";
import { ElLoading, ElMessage } from "element-plus";
import "element-plus/es/components/loading/style/css";
import "element-plus/es/components/message/style/css";
import store from "@/store";
import router from "@/router";

export const baseURL = window.baseUrl;
let loading;
// 封装axios
const service = axios.create({
  baseURL, // api的base_url
  timeout: 10000, // 请求超时时间
});

service.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = "Bearer " + store.getters.token;

    return config;
  },
  (error) => {
    loading.close();
    ElMessage.error("请求超时");
    return Promise.reject(error);
  }
);
// 响应拦截
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response.status == 401) {
      ElMessage.error(error.response.data.msg);
      store.commit("clearUserInfo");
      router.push("/login");
    } else {
      ElMessage.error("服务器错误");
    }
    return Promise.reject(error);
  }
);

const request = (
  AxiosConfig,
  costomConfig = {
    isloading: true,
  }
) => {
  return new Promise((reslove, reject) => {
    if (costomConfig) {
      if (costomConfig.isloading) {
        loading = ElLoading.service({ text: "加载中..." });
      }
    }
    service(AxiosConfig)
      .then((res) => {
        reslove(res);
        loading && loading.close();
      })
      .catch((e) => {
        reject(e);
        loading && loading.close();
      });
  });
};

export default request;
